package com.ecube.maintenance.managers;

import android.content.Context;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.navisdk.BaiduNaviManager;
import com.ecube.maintenance.pojos.AddressInfo;

/**
 * Created by Trible Chen on 2014/9/9.
 */
public class LocationBDManager {

    Context mContext;
    LocationClient locationClient;
    BDLocationListener mListener;

    private static LocationBDManager ourInstance = new LocationBDManager();

    public static LocationBDManager getInstance() {
        return ourInstance;
    }

    private LocationBDManager() {
    }

    public static void init(Context context){
        getInstance().mContext = context;
        SDKInitializer.initialize(context.getApplicationContext());
        getInstance().locationClient = new LocationClient(context.getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置定位模式
        option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
        option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
        option.setIsNeedAddress(true);//返回的定位结果包含地址信息
        option.setOpenGps(true);
        getInstance().locationClient.setLocOption(option);
        getInstance().locationClient.setDebug(true);

    }

    public static void requestLocation( MyBDLocationListener listener){
        if ( getInstance().mListener != listener ){
            getInstance().mListener = listener;
            getInstance().locationClient.registerLocationListener(listener);
        }
        getInstance().locationClient.start();
        getInstance().locationClient.requestLocation();
    }

    public static abstract class MyBDLocationListener implements BDLocationListener{
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            AddressInfo info = new AddressInfo();
            if ( bdLocation != null && bdLocation.hasAddr()){
                info.setLat(bdLocation.getLatitude());
                info.setLon(bdLocation.getLongitude());
                String city = bdLocation.getCity();
                int idx = city.indexOf("市");
                if ( idx != -1 ){
                    city = city.substring(0,idx);
                }
                info.setAddress(city);
                onReceive(info);
            } else {
                onReceive(null);
            }
            getInstance().locationClient.stop();
        }
        protected  abstract void onReceive(AddressInfo info);
    }


}
